In [1]:
import numpy as np
In [29]:
#sort():
a=np.array([5,1,3,6,4])
print(np.sort(a))
print(np.sort(a)[::-1])
print(a)
a.sort()
print(a)
[1 3 4 5 6]
[6 5 4 3 1]
[5 1 3 6 4]
[1 3 4 5 6]
In [13]:
b=np.random.randint(1,100,24).reshape(6,4)
print(b)
print()
print(np.sort(b,axis=0))
print()
print(np.sort(b,axis=1))
[[59 79 83 12]
 [57 43 92 99]
 [29 81 85 38]
 [90 85 49 75]
 [70 30 94 69]
 [86 99 84 43]]

[[29 30 49 12]
 [57 43 83 38]
 [59 79 84 43]
 [70 81 85 69]
 [86 85 92 75]
 [90 99 94 99]]

[[12 59 79 83]
 [43 57 92 99]
 [29 38 81 85]
 [49 75 85 90]
 [30 69 70 94]
 [43 84 86 99]]
In [15]:
#split
a=np.array([1,2,3,4,5,6])
new=np.array_split(a,3)
print(new)
print(np.array_split(a,4))
[array([1, 2]), array([3, 4]), array([5, 6])]
[array([1, 2]), array([3, 4]), array([5]), array([6])]
In [21]:
arr=np.array([[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]])
print(np.array_split(arr,3))
print()
print(np.array_split(arr,3,axis=1))
print()
print(np.array_split(arr,3,axis=0))
[array([[1, 2],
       [3, 4]]), array([[5, 6],
       [7, 8]]), array([[ 9, 10],
       [11, 12]])]
[array([[ 1],
       [ 3],
       [ 5],
       [ 7],
       [ 9],
       [11]]), array([[ 2],
       [ 4],
       [ 6],
       [ 8],
       [10],
       [12]]), array([], shape=(6, 0), dtype=int32)]
[array([[1, 2],
       [3, 4]]), array([[5, 6],
       [7, 8]]), array([[ 9, 10],
       [11, 12]])]
In [28]:
x=np.array([1,2,3,4,5])
for i in x:
    print(i)
y=np.array([[1,2],[3,4]])
for j in y:
    print(j)
    
for i in np.nditer(x):
    print(i)
1
2
3
4
5
[1 2]
[3 4]
1
2
3
4
5
In [42]:
#polymorphism
#(method overloading)
class pyprog:
    def __init__(self,name):
        self.name=name
    def show(self):
        print("creater of python:",self.name)
class javapro:
    def __init__(self,name):
        self.name=name
    def show(self):
        print("creater of java is:",self.name)

        
p1=pyprog("rajan")
p1.show()
p2=javapro("harsh")
p2.show()
creater of python: rajan
creater of java is: harsh
In [43]:
#single level inheritance
class person:
    def __init__(self,name):
        self.name=name
    def show(self):
        print("creater of python:",self.name)
class professor(person):
    pass
p1=professor("rajan")
p1.show()
   
creater of python: rajan
In [44]:
#hyrarcy
class person:
    def __init__(self,name):
        self.name=name
    def show(self):
        print("creater of python:",self.name)
class professor(person):
    pass
class teacher(professor):
    pass
p1=teacher("rajan")
p1.show()
creater of python: rajan
In [47]:
#multiple inheritance
class person:
    def __init__(self,name):
        self.name=name
    def show(self):
        print("creater of python:",self.name)
class professor:
    def credit(self):
        print("he teacher python")
class teacher(person,professor):
    pass
p1=teacher("rajan")
p1.show()
p1.credit()
    
creater of python: rajan
he teacher python
In [48]:
#super().___()
class Myclass:
    def fun(self):
        print("from parent")
class child(Myclass):
    def fun(self):
        print("from child")
        super().fun()
        print("back to child")
a1=child()
a1.fun()
from child
from parent
back to child
In [4]:
#[absract class]: this class is derived from abc import ABC (abstarct base class),ABC
#is a meta class which defines behaviour of other class
# abstarct method of an  abstarct class must be defined in child class.
#It is use when common fetures are shared by all objects
# as they are.


#ex:from abc import ABC,abstarctmethod

from abc import ABC,abstractmethod
class Defence(ABC):
    @abstractmethod
    def area(Self):
        pass
    def gun(self):
        print("Gun is AK-47")
class Army(Defence):
    def area(self):
        print("area is land")
class Navy(Defence):
    def area(Self):
        print("area is sea")
        
a=Army()
b=Navy()
a.area()
a.gun()
b.area()
b.gun()
area is land
Gun is AK-47
area is sea
Gun is AK-47
In [10]:
#METHOD RESOLUTION ORDER:-
class A:
    def which(self):
        print("I am from A")
class B(A):
    def which(self):
        print("I am from B")
class C(A):
    def which(self):
        print("I am from C")
class D(C,B):
    def which(self):
        print("I am from D")
d=D()
d.which()
D.mro()  # type D and press . and select mro      
    
I am from C
Out[10]:
[__main__.D, __main__.C, __main__.B, __main__.A, object]
In [9]:
# C3, linearization algoritham: child have a heighest priority or left to right tarvers
class F:
    pass
class E:
    pass
class D:
    pass
class C(D,F):
    pass
class B(D,E):
    pass
class A(B,C):
    pass
A.mro()

"""step:1 >MRO of D,E,F:-
     L(D)=DO
     L(E)=EO
     L(F)=FO
    """
    
Out[9]:
[__main__.A,
 __main__.B,
 __main__.C,
 __main__.D,
 __main__.E,
 __main__.F,
 object]
In [11]:
class A:
    pass
class B:
    pass
class C(A,B):
    pass
class D(B,A):
    pass
class X(C,D):
    pass
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-e6066b25c528> in <module>
      7 class D(B,A):
      8     pass
----> 9 class X(C,D):
     10     pass

TypeError: Cannot create a consistent method resolution
order (MRO) for bases A, B
In [13]:
class A:
    pass
class B:
    pass
class C(A,B):
    pass
class D(C,B):
    pass
class E(D,C):
    pass
In [14]:
# DUNDER /SPECIAL/MAGIC METHOD
class Book:
    def __init__(self,title,author,pages):
        print("A book crated")
        self.title=title
        self.author=author
        self.pages=pages
    def __str__(self):
        return f"A {self.title} book by {self.author}"
    def __len__(self):
        return self.pages
    def __del__(self):
        print("book destroyed")
In [2]:
pip install plotly
Collecting plotly
  Downloading plotly-5.18.0-py3-none-any.whl (15.6 MB)
Collecting tenacity>=6.2.0
  Downloading tenacity-8.2.3-py3-none-any.whl (24 kB)
Requirement already satisfied: packaging in c:\programdata\anaconda3\lib\site-packages (from plotly) (20.4)
Requirement already satisfied: pyparsing>=2.0.2 in c:\programdata\anaconda3\lib\site-packages (from packaging->plotly) (2.4.7)
Requirement already satisfied: six in c:\programdata\anaconda3\lib\site-packages (from packaging->plotly) (1.15.0)
Installing collected packages: tenacity, plotly
Successfully installed plotly-5.18.0 tenacity-8.2.3
Note: you may need to restart the kernel to use updated packages.
In [3]:
import plotly.express as px

fig = px.line(x=["a","b","c"], y=[1,3,2], title="sample figure")
print(fig)
fig.show()
Figure({
    'data': [{'hovertemplate': 'x=%{x}<br>y=%{y}<extra></extra>',
              'legendgroup': '',
              'line': {'color': '#636efa', 'dash': 'solid'},
              'marker': {'symbol': 'circle'},
              'mode': 'lines',
              'name': '',
              'orientation': 'v',
              'showlegend': False,
              'type': 'scatter',
              'x': array(['a', 'b', 'c'], dtype=object),
              'xaxis': 'x',
              'y': array([1, 3, 2], dtype=int64),
              'yaxis': 'y'}],
    'layout': {'legend': {'tracegroupgap': 0},
               'template': '...',
               'title': {'text': 'sample figure'},
               'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'x'}},
               'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'y'}}}
})
In [9]:
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Europe'")
df.loc[df['pop'] < 2.e6, 'country'] = 'Other countries' # Represent only large countries
fig = px.pie(df, values='pop', names='country', title='Population of European continent')
fig.show()
In [13]:
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill", y="tip", color="sex", marginal="rug",
                   hover_data=df.columns)
fig.show()
In [12]:
import matplotlib.pyplot as plt
In [15]:
import numpy as np
import matplotlib.pyplot as plt
In [27]:
x=np.linspace(0,4*np.pi,100)
y=np.sin(x)
In [28]:
fig, ax=plt.subplots()
ax.plot(x,y)
plt.show()
In [33]:
plt.title("hi rajan")
plt.grid()
In [39]:
x=np.linspace(0,10,100)
y1,y2=np.sin(x),np.cos(x)
plt.plot(x,y1,x,y2)
Out[39]:
[<matplotlib.lines.Line2D at 0x2407cdfd4f0>,
 <matplotlib.lines.Line2D at 0x2407cdfd2e0>]
In [40]:
fig, (ax1,ax2)=plt.subplots(2,1)
ax1.plot(x,y1,color="pink")
ax2.plot(x,y2,color="green")
Out[40]:
[<matplotlib.lines.Line2D at 0x2407cffb880>]
In [2]:
import matplotlib.pyplot as plt
In [2]:
# x axis element
x=[1,2,3]
# y axis element
y=[2,4,1]
plt.plot(x,y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("my first graph")
plt.show()
In [3]:
# x axis element
x1=[1,2,3]
# y axis element
y1=[2,4,1]
plt.plot(x1,y1,label="line-1")
x2=[1,2,3]
y2=[4,1,3]
plt.plot(x2,y2,label="line-2")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("two lines on same graph")
plt.legend()
plt.show()
In [8]:
value=[5,6,13,7,2]
name=["A","B","C","D","E"]
plt.title("Bar graphs")
plt.bar(name,value,color="red")
plt.show()
In [11]:
x=[1,2,3,4,5,6]
y=[2,4,1,2,3,7]
plt.plot(x,y,color="blue",linestyle="dashed",linewidth=3,
        marker='o',markerfacecolor='red',markersize=12)
plt.ylim(1,8)
plt.xlim(1,8)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title("some coll customizations!")
plt.show()
In [13]:
help(plt.plot)
Help on function plot in module matplotlib.pyplot:

plot(*args, scalex=True, scaley=True, data=None, **kwargs)
    Plot y versus x as lines and/or markers.
    
    Call signatures::
    
        plot([x], y, [fmt], *, data=None, **kwargs)
        plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
    
    The coordinates of the points or line nodes are given by *x*, *y*.
    
    The optional parameter *fmt* is a convenient way for defining basic
    formatting like color, marker and linestyle. It's a shortcut string
    notation described in the *Notes* section below.
    
    >>> plot(x, y)        # plot x and y using default line style and color
    >>> plot(x, y, 'bo')  # plot x and y using blue circle markers
    >>> plot(y)           # plot y using x as index array 0..N-1
    >>> plot(y, 'r+')     # ditto, but with red plusses
    
    You can use `.Line2D` properties as keyword arguments for more
    control on the appearance. Line properties and *fmt* can be mixed.
    The following two calls yield identical results:
    
    >>> plot(x, y, 'go--', linewidth=2, markersize=12)
    >>> plot(x, y, color='green', marker='o', linestyle='dashed',
    ...      linewidth=2, markersize=12)
    
    When conflicting with *fmt*, keyword arguments take precedence.
    
    
    **Plotting labelled data**
    
    There's a convenient way for plotting objects with labelled data (i.e.
    data that can be accessed by index ``obj['y']``). Instead of giving
    the data in *x* and *y*, you can provide the object in the *data*
    parameter and just give the labels for *x* and *y*::
    
    >>> plot('xlabel', 'ylabel', data=obj)
    
    All indexable objects are supported. This could e.g. be a `dict`, a
    `pandas.DataFrame` or a structured numpy array.
    
    
    **Plotting multiple sets of data**
    
    There are various ways to plot multiple sets of data.
    
    - The most straight forward way is just to call `plot` multiple times.
      Example:
    
      >>> plot(x1, y1, 'bo')
      >>> plot(x2, y2, 'go')
    
    - Alternatively, if your data is already a 2d array, you can pass it
      directly to *x*, *y*. A separate data set will be drawn for every
      column.
    
      Example: an array ``a`` where the first column represents the *x*
      values and the other columns are the *y* columns::
    
      >>> plot(a[0], a[1:])
    
    - The third way is to specify multiple sets of *[x]*, *y*, *[fmt]*
      groups::
    
      >>> plot(x1, y1, 'g^', x2, y2, 'g-')
    
      In this case, any additional keyword argument applies to all
      datasets. Also this syntax cannot be combined with the *data*
      parameter.
    
    By default, each line is assigned a different style specified by a
    'style cycle'. The *fmt* and line property parameters are only
    necessary if you want explicit deviations from these defaults.
    Alternatively, you can also change the style cycle using
    :rc:`axes.prop_cycle`.
    
    
    Parameters
    ----------
    x, y : array-like or scalar
        The horizontal / vertical coordinates of the data points.
        *x* values are optional and default to ``range(len(y))``.
    
        Commonly, these parameters are 1D arrays.
    
        They can also be scalars, or two-dimensional (in that case, the
        columns represent separate data sets).
    
        These arguments cannot be passed as keywords.
    
    fmt : str, optional
        A format string, e.g. 'ro' for red circles. See the *Notes*
        section for a full description of the format strings.
    
        Format strings are just an abbreviation for quickly setting
        basic line properties. All of these and more can also be
        controlled by keyword arguments.
    
        This argument cannot be passed as keyword.
    
    data : indexable object, optional
        An object with labelled data. If given, provide the label names to
        plot in *x* and *y*.
    
        .. note::
            Technically there's a slight ambiguity in calls where the
            second label is a valid *fmt*. ``plot('n', 'o', data=obj)``
            could be ``plt(x, y)`` or ``plt(y, fmt)``. In such cases,
            the former interpretation is chosen, but a warning is issued.
            You may suppress the warning by adding an empty format string
            ``plot('n', 'o', '', data=obj)``.
    
    Returns
    -------
    list of `.Line2D`
        A list of lines representing the plotted data.
    
    Other Parameters
    ----------------
    scalex, scaley : bool, default: True
        These parameters determine if the view limits are adapted to the
        data limits. The values are passed on to `autoscale_view`.
    
    **kwargs : `.Line2D` properties, optional
        *kwargs* are used to specify properties like a line label (for
        auto legends), linewidth, antialiasing, marker face color.
        Example::
    
        >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)
        >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
    
        If you make multiple lines with one plot call, the kwargs
        apply to all those lines.
    
        Here is a list of available `.Line2D` properties:
    
        Properties:
        agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
        alpha: float or None
        animated: bool
        antialiased or aa: bool
        clip_box: `.Bbox`
        clip_on: bool
        clip_path: Patch or (Path, Transform) or None
        color or c: color
        contains: unknown
        dash_capstyle: {'butt', 'round', 'projecting'}
        dash_joinstyle: {'miter', 'round', 'bevel'}
        dashes: sequence of floats (on/off ink in points) or (None, None)
        data: (2, N) array or two 1D arrays
        drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
        figure: `.Figure`
        fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'}
        gid: str
        in_layout: bool
        label: object
        linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
        linewidth or lw: float
        marker: marker style string, `~.path.Path` or `~.markers.MarkerStyle`
        markeredgecolor or mec: color
        markeredgewidth or mew: float
        markerfacecolor or mfc: color
        markerfacecoloralt or mfcalt: color
        markersize or ms: float
        markevery: None or int or (int, int) or slice or List[int] or float or (float, float) or List[bool]
        path_effects: `.AbstractPathEffect`
        picker: unknown
        pickradius: float
        rasterized: bool or None
        sketch_params: (scale: float, length: float, randomness: float)
        snap: bool or None
        solid_capstyle: {'butt', 'round', 'projecting'}
        solid_joinstyle: {'miter', 'round', 'bevel'}
        transform: `matplotlib.transforms.Transform`
        url: str
        visible: bool
        xdata: 1D array
        ydata: 1D array
        zorder: float
    
    See Also
    --------
    scatter : XY scatter plot with markers of varying size and/or color (
        sometimes also called bubble chart).
    
    Notes
    -----
    **Format Strings**
    
    A format string consists of a part for color, marker and line::
    
        fmt = '[marker][line][color]'
    
    Each of them is optional. If not provided, the value from the style
    cycle is used. Exception: If ``line`` is given, but no ``marker``,
    the data will be a line without markers.
    
    Other combinations such as ``[color][marker][line]`` are also
    supported, but note that their parsing may be ambiguous.
    
    **Markers**
    
    =============    ===============================
    character        description
    =============    ===============================
    ``'.'``          point marker
    ``','``          pixel marker
    ``'o'``          circle marker
    ``'v'``          triangle_down marker
    ``'^'``          triangle_up marker
    ``'<'``          triangle_left marker
    ``'>'``          triangle_right marker
    ``'1'``          tri_down marker
    ``'2'``          tri_up marker
    ``'3'``          tri_left marker
    ``'4'``          tri_right marker
    ``'s'``          square marker
    ``'p'``          pentagon marker
    ``'*'``          star marker
    ``'h'``          hexagon1 marker
    ``'H'``          hexagon2 marker
    ``'+'``          plus marker
    ``'x'``          x marker
    ``'D'``          diamond marker
    ``'d'``          thin_diamond marker
    ``'|'``          vline marker
    ``'_'``          hline marker
    =============    ===============================
    
    **Line Styles**
    
    =============    ===============================
    character        description
    =============    ===============================
    ``'-'``          solid line style
    ``'--'``         dashed line style
    ``'-.'``         dash-dot line style
    ``':'``          dotted line style
    =============    ===============================
    
    Example format strings::
    
        'b'    # blue markers with default shape
        'or'   # red circles
        '-g'   # green solid line
        '--'   # dashed line with default color
        '^k:'  # black triangle_up markers connected by a dotted line
    
    **Colors**
    
    The supported color abbreviations are the single letter codes
    
    =============    ===============================
    character        color
    =============    ===============================
    ``'b'``          blue
    ``'g'``          green
    ``'r'``          red
    ``'c'``          cyan
    ``'m'``          magenta
    ``'y'``          yellow
    ``'k'``          black
    ``'w'``          white
    =============    ===============================
    
    and the ``'CN'`` colors that index into the default property cycle.
    
    If the color is the only part of the format string, you can
    additionally use any  `matplotlib.colors` spec, e.g. full names
    (``'green'``) or hex strings (``'#008000'``).

In [15]:
#histogram
ages=[2,5,70,40,30,45,43,40,44,60,7,13,57,18,90,77,32,21,20,40]
range=(0,100)
bins=10
plt.hist(ages,bins,range,color='green',histtype='bar',rwidth=0.8)
plt.xlabel("age")
plt.ylabel('no of people')
plt.title("my histogram")
plt.show()
In [20]:
activities=['eat','sleep','work','play']
slices=[3,7,8,6]
colors=['r','y','g','b']
plt.pie(slices,labels=activities,colors=colors,
       startangle=90,shadow=True,explode=(0,0,0.1,0),radius=1.2,autopct='%1.1f%%')
plt.legend()
plt.show()
#counterclock=false for chage the direction of analysis
In [18]:
help(plt.pie)
Help on function pie in module matplotlib.pyplot:

pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, normalize=None, data=None)
    Plot a pie chart.
    
    Make a pie chart of array *x*.  The fractional area of each wedge is
    given by ``x/sum(x)``.  If ``sum(x) < 1``, then the values of *x* give
    the fractional area directly and the array will not be normalized. The
    resulting pie will have an empty wedge of size ``1 - sum(x)``.
    
    The wedges are plotted counterclockwise, by default starting from the
    x-axis.
    
    Parameters
    ----------
    x : 1D array-like
        The wedge sizes.
    
    explode : array-like, default: None
        If not *None*, is a ``len(x)`` array which specifies the fraction
        of the radius with which to offset each wedge.
    
    labels : list, default: None
        A sequence of strings providing the labels for each wedge
    
    colors : array-like, default: None
        A sequence of colors through which the pie chart will cycle.  If
        *None*, will use the colors in the currently active cycle.
    
    autopct : None or str or callable, default: None
        If not *None*, is a string or function used to label the wedges
        with their numeric value.  The label will be placed inside the
        wedge.  If it is a format string, the label will be ``fmt % pct``.
        If it is a function, it will be called.
    
    pctdistance : float, default: 0.6
        The ratio between the center of each pie slice and the start of
        the text generated by *autopct*.  Ignored if *autopct* is *None*.
    
    shadow : bool, default: False
        Draw a shadow beneath the pie.
    
    normalize: None or bool, default: None
        When *True*, always make a full pie by normalizing x so that
        ``sum(x) == 1``. *False* makes a partial pie if ``sum(x) <= 1``
        and raises a `ValueError` for ``sum(x) > 1``.
    
        When *None*, defaults to *True* if ``sum(x) >= 1`` and *False* if
        ``sum(x) < 1``.
    
        Please note that the previous default value of *None* is now
        deprecated, and the default will change to *True* in the next
        release. Please pass ``normalize=False`` explicitly if you want to
        draw a partial pie.
    
    labeldistance : float or None, default: 1.1
        The radial distance at which the pie labels are drawn.
        If set to ``None``, label are not drawn, but are stored for use in
        ``legend()``
    
    startangle : float, default: 0 degrees
        The angle by which the start of the pie is rotated,
        counterclockwise from the x-axis.
    
    radius : float, default: 1
        The radius of the pie.
    
    counterclock : bool, default: True
        Specify fractions direction, clockwise or counterclockwise.
    
    wedgeprops : dict, default: None
        Dict of arguments passed to the wedge objects making the pie.
        For example, you can pass in ``wedgeprops = {'linewidth': 3}``
        to set the width of the wedge border lines equal to 3.
        For more details, look at the doc/arguments of the wedge object.
        By default ``clip_on=False``.
    
    textprops : dict, default: None
        Dict of arguments to pass to the text objects.
    
    center : (float, float), default: (0, 0)
        The coordinates of the center of the chart.
    
    frame : bool, default: False
        Plot axes frame with the chart if true.
    
    rotatelabels : bool, default: False
        Rotate each label to the angle of the corresponding slice if true.
    
    Returns
    -------
    patches : list
        A sequence of `matplotlib.patches.Wedge` instances
    
    texts : list
        A list of the label `.Text` instances.
    
    autotexts : list
        A list of `.Text` instances for the numeric labels. This will only
        be returned if the parameter *autopct* is not *None*.
    
    Notes
    -----
    The pie chart will probably look best if the figure and axes are
    square, or the Axes aspect is equal.
    This method sets the aspect ratio of the axis to "equal".
    The axes aspect ratio can be controlled with `.Axes.set_aspect`.
    
    .. note::
        In addition to the above described arguments, this function can take
        a *data* keyword argument. If such a *data* argument is given,
        the following arguments can also be string ``s``, which is
        interpreted as ``data[s]`` (unless this raises an exception):
        *x*, *explode*, *labels*, *colors*.
    
        Objects passed as **data** must support item access (``data[s]``) and
        membership test (``s in data``).

In [10]:
# x axis element
x1=[10,20,30]
# y axis element

y1=[20,40,10]
plt.plot(x1,y1,label="line-1")
x2=[1,2,3]
y2=[4,1,3]
plt.plot(x2,y2,label="line-2")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("two lines on same graph")
plt.legend()
plt.show()
In [6]:
weight1 = [67, 57.2, 59.6, 59.64, 55.8, 61.2, 60.45, 61, 56.23, 56]
height1 = [101.7, 197.6, 98.3, 125.1, 113.7, 157.7, 136, 148.9, 125.3, 114.9]
weight2 = [61.9, 64, 62.1, 64.2, 62.3, 65.4, 62.4, 61.4, 62.5, 63.6]
height2 = [152.8, 155.3, 135.1, 125.2, 151.3, 135, 182.2, 195.9, 165.1, 125.1]
weight3 = [68.2, 67.2, 68.4, 68.7, 71, 71.3, 70.8, 70, 71.1, 71.7]
height3 = [165.8, 170.9, 192.8, 135.4, 161.4, 136.1, 167.1, 235.1, 181.1, 177.3]
plt.scatter(weight1,height1,label='star',color="green",marker="*",s=30)
plt.scatter(weight2,height2,label='star',color="red",marker="*",s=30)
plt.scatter(weight3,height3,label='star',color="blue",marker="*",s=30)

plt.xlabel("weight")
plt.ylabel("height")
plt.title("exercise 2")
plt.legend()
plt.show()
In [12]:
value=[22.2, 17.6, 8.8, 8, 7.7, 6.7]
name=["A","B","C","D","E","F"]
plt.title("Bar graphs")
plt.bar(name,value,color="red")
plt.show()
In [17]:
activities=['eat','sleep','work','play']
slices=[3,7,8,6]
colors=['r','y','g','b']
plt.pie(slices,labels=activities,colors=colors,
       startangle=90,shadow=True,explode=(0,0,0.1,0),radius=1.2,autopct='%1.1f%%')
plt.legend()
plt.show()
In [19]:
# x axis element
x1=[10,20,30]
# y axis element
plt.subplot(2,1,1)
y1=[20,40,10]
plt.plot(x1,y1,label="line-1")
x2=[1,2,3]
y2=[4,1,3]
plt.plot(x2,y2,label="line-2")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("two lines on same graph")
plt.legend()
plt.show()
plt.subplot(2,3,4)
weight1 = [67, 57.2, 59.6, 59.64, 55.8, 61.2, 60.45, 61, 56.23, 56]
height1 = [101.7, 197.6, 98.3, 125.1, 113.7, 157.7, 136, 148.9, 125.3, 114.9]
weight2 = [61.9, 64, 62.1, 64.2, 62.3, 65.4, 62.4, 61.4, 62.5, 63.6]
height2 = [152.8, 155.3, 135.1, 125.2, 151.3, 135, 182.2, 195.9, 165.1, 125.1]
weight3 = [68.2, 67.2, 68.4, 68.7, 71, 71.3, 70.8, 70, 71.1, 71.7]
height3 = [165.8, 170.9, 192.8, 135.4, 161.4, 136.1, 167.1, 235.1, 181.1, 177.3]
plt.scatter(weight1,height1,label='star',color="green",marker="*",s=30)
plt.scatter(weight2,height2,label='star',color="red",marker="*",s=30)
plt.scatter(weight3,height3,label='star',color="blue",marker="*",s=30)

plt.xlabel("weight")
plt.ylabel("height")
plt.title("exercise 2")
plt.legend()

plt.subplot(2,3,5)
value=[22.2, 17.6, 8.8, 8, 7.7, 6.7]
name=["A","B","C","D","E","F"]
plt.title("Bar graphs")
plt.bar(name,value,color="red")

plt.subplot(2,3,6)
activities=['eat','sleep','work','play']
slices=[3,7,8,6]
colors=['r','y','g','b']
plt.pie(slices,labels=activities,colors=colors,
       startangle=90,shadow=True,explode=(0,0,0.1,0),radius=1.2,autopct='%1.1f%%')
plt.legend()
plt.show()
In [ ]: